import React, { useEffect, useState } from 'react';
import { connect } from 'umi';
import { Modal, Steps, Button, Form, Input, Select, Row, Col, Divider } from 'antd';
import EditorInput from '@/components/EditorInput';
import UploadInput from '@/components/UploadInput';
import { formatMsgTime } from '@/utils/format';
import { TOKEN_KEY, getCookie } from '@/utils/cookie';

const { Option } = Select;

const LegalAffairsAddModal = ({ dispatch, actionRef, loading, pubList }) => {
  const [form] = Form.useForm();
  const [stepCurrent, setCurrent] = useState(0);
  const [informationId, setInformationId] = useState('');
  const [LegalAffairsAddModalVisible, setLegalAffairsAddModalVisible] = useState(false);
  const typeInfo = {
    POLICY_GUIDE: '政策指南',
    LEGAL_DYNAMIC: '法务动态',
    INTERNATIONAL_NEWS: '国际要闻',
    ANNOUNCEMENT: '通知公告',
  };

  const showModal = infoId => {
    form.resetFields();
    if (infoId) {
      setCurrent(1);
      setInformationId(infoId);
      getInfoOpenDetail(infoId);
    }
    setLegalAffairsAddModalVisible(true);
  };

  const getInfoOpenDetail = id => {
    new Promise(resolve => {
      dispatch({
        type: 'informationOpen/getInfoOpenDetail',
        payload: { id },
        resolve,
      });
    }).then(data => {
      const fields = {
        ...data,

        cover: data.cover && [
          {
            url: data.cover.url,
            uid: data.cover.id,
            name: data.cover.name,
            status: 'done',
          },
        ],
        media: data.media && [
          {
            url: data.media.url,
            uid: data.media.id,
            name: data.media.name,
            status: 'done',
          },
        ],
        attachment: JSON.parse(JSON.stringify(data.attachment).replace(/id/g, 'uid')),
      };

      form.setFieldsValue(fields);
    });
  };

  useEffect(() => {
    if (actionRef && typeof actionRef === 'function') {
      actionRef({ showModal });
    }
    if (actionRef && typeof actionRef !== 'function') {
      actionRef.current = { showModal };
    }
  }, []);

  useEffect(() => {
    dispatch({
      type: 'informationOpen/getPubList',
      payload: {
        Authentication: getCookie(TOKEN_KEY),
      },
    })
      .then()
      .catch();
  }, []);

  const changeCurrent = index => {
    form.validateFields().then(_ => {
      setCurrent(index);
    });
  };

  const hideModal = () => {
    setLegalAffairsAddModalVisible(false);
    changeCurrent(0);
    setInformationId('');
    form.resetFields();
  };

  const steps = [
    {
      title: '完善基本信息',
      effect: 'updateBasicInfo',
    },
    {
      title: '编辑正文',
      effect: 'updateText',
    },
    {
      title: '预览和提交',
      effect: 'previewAndSubmit',
    },
  ];

  const handleOk = () => {
    const attachmentInfo = [];
    form.getFieldValue(['attachment']) &&
      form.getFieldValue(['attachment']).map(item => attachmentInfo.push(item.uid));
    new Promise(resolve => {
      dispatch({
        type: `informationOpen/${informationId ? 'updateInfoOpen' : 'addInfoOpen'}`,
        payload: {
          ...form.getFieldsValue(['title', 'type', 'publishBy', 'summary', 'text']),
          media: form.getFieldValue(['media']) && form.getFieldValue(['media'])[0].uid,
          cover: form.getFieldValue(['cover']) && form.getFieldValue(['cover'])[0].uid,
          attachment: attachmentInfo || undefined,
          id: informationId || undefined,
        },
        resolve,
      });
    })
      .then(() => {
        hideModal();
      })
      .catch();
  };

  return (
    <Modal
      title="创建新的信息公开"
      centered
      width="95vw"
      style={{ paddingBottom: 0 }}
      bodyStyle={{
        height: 'calc(95vh - 108px)',
        overflow: 'auto',
      }}
      visible={LegalAffairsAddModalVisible}
      forceRender
      footer={[
        stepCurrent === 2 && (
          <Button key="cancel" onClick={hideModal}>
            退出
          </Button>
        ),

        stepCurrent === 2 && (
          <Button key="pre" type="primary" onClick={() => changeCurrent(stepCurrent - 1)}>
            返回编辑
          </Button>
        ),
        stepCurrent === 0 && (
          <Button key="next" type="primary" onClick={() => changeCurrent(stepCurrent + 1)}>
            下一步
          </Button>
        ),
        stepCurrent === 1 && (
          <Button key="next" type="primary" onClick={() => changeCurrent(stepCurrent + 1)}>
            预览并发布
          </Button>
        ),
        stepCurrent === 2 && (
          <Button key="submit" type="primary" loading={loading} onClick={handleOk}>
            发布
          </Button>
        ),
      ]}
      maskClosable={false}
      destroyOnClose
      onCancel={hideModal}
    >
      <Steps current={stepCurrent}>
        {steps.map(item => (
          <Steps.Step key={item.title} title={item.title} />
        ))}
      </Steps>
      <div
        style={{
          height: 'calc(100% - 36px)',
          padding: '20px 0',
          overflowX: 'hidden',
          boxSizing: 'border-box',
        }}
      >
        {stepCurrent === 0 && (
          <div>
            <div
              style={{
                textAlign: 'center',
                fontSize: '20px',
                fontWeight: '700',
                marginBottom: '20px',
              }}
            >
              欢迎使用天府法务平台
            </div>
            <div style={{ textAlign: 'center', fontSize: '16px', marginBottom: 20 }}>
              请完善以下基本信息
            </div>
          </div>
        )}

        <Form name="info" layout="vertical" form={form}>
          <div style={{ display: 'flex', justifyContent: 'center' }}>
            {stepCurrent === 0 && (
              <div style={{ width: '33.3%', minWidth: 450 }}>
                <Form.Item
                  label="标题"
                  name="title"
                  rules={[{ required: true, message: '请输入标题!' }]}
                >
                  <Input />
                </Form.Item>
                <Form.Item
                  label="类型"
                  name="type"
                  rules={[{ required: true, message: '请选择类型!' }]}
                >
                  <Select allowClear>
                    <Option value="POLICY_GUIDE">政策指南</Option>
                    <Option value="LEGAL_DYNAMIC">法务动态</Option>
                    <Option value="INTERNATIONAL_NEWS">国际要闻</Option>
                    <Option value="ANNOUNCEMENT">通知公告</Option>
                  </Select>
                </Form.Item>

                <Form.Item label="附件" name="attachment">
                  <UploadInput type="upload" />
                </Form.Item>
              </div>
            )}
          </div>
          {stepCurrent === 1 && (
            <div style={{ display: 'flex', justifyContent: 'center' }}>
              <div style={{ width: '60%', minWidth: 850, maxWidth: 850 }}>
                <Row>
                  <Col span="11">
                    <Form.Item
                      label="类型"
                      name="type"
                      rules={[{ required: true, message: '请选择类型!' }]}
                    >
                      <Select allowClear>
                        <Option value="POLICY_GUIDE">政策指南</Option>
                        <Option value="LEGAL_DYNAMIC">法务动态</Option>
                        <Option value="INTERNATIONAL_NEWS">国际要闻</Option>
                        <Option value="ANNOUNCEMENT">通知公告</Option>
                      </Select>
                    </Form.Item>
                  </Col>
                  <Col span="11" offset="2">
                    <Form.Item
                      label="发布人"
                      name="publishBy"
                      rules={[{ required: true, message: '请选择发布人!' }]}
                    >
                      <Select allowClear>
                        {pubList &&
                          pubList.map(item => (
                            <Option key={item.id} value={item.id}>
                              {item.nickname}
                            </Option>
                          ))}
                      </Select>
                    </Form.Item>
                  </Col>
                </Row>
                <Row>
                  <Col span="24">
                    <Form.Item name="text">
                      <EditorInput />
                    </Form.Item>
                  </Col>
                </Row>
                <Divider />
                <Row>
                  <Col span="4">
                    <Form.Item label="封面" name="cover">
                      <UploadInput type="image" />
                    </Form.Item>
                  </Col>
                  <Col span="19" offset="1">
                    <Form.Item label="摘要" name="summary">
                      <Input.TextArea rows={4} placeholder="选填，摘要。" />
                    </Form.Item>
                  </Col>
                </Row>
                <Divider />
                <Row>
                  <Col span="24">
                    <Form.Item label="附件" name="attachment">
                      <UploadInput type="upload" />
                    </Form.Item>
                  </Col>
                </Row>
                <Divider />
                <Row>
                  <Col span="24">
                    <Form.Item label="视频" name="media">
                      <UploadInput type="vedio" />
                    </Form.Item>
                  </Col>
                </Row>
              </div>
            </div>
          )}
          {stepCurrent === 2 && (
            <div style={{ display: 'flex', justifyContent: 'center' }}>
              <div style={{ width: '60%', minWidth: 850, maxWidth: 850 }}>
                <div
                  style={{
                    textAlign: 'center',
                    fontSize: '20px',
                    fontWeight: '700',
                    marginBottom: '20px',
                  }}
                >
                  {form.getFieldValue('title')}
                </div>
                <div
                  style={{
                    fontSize: '14px',
                    marginBottom: '20px',
                  }}
                >
                  {form.getFieldValue('publishBy')}（发布人）
                  <Divider type="vertical" style={{ color: 'black' }} />
                  {formatMsgTime(new Date())}（发布时间）
                  <Divider type="vertical" />
                  {typeInfo[form.getFieldValue('type')]}（发布类型）
                </div>
                <div dangerouslySetInnerHTML={{ __html: form.getFieldValue('text') }} />
                {/* {form.getFieldValue('att') && form.getFieldValue('att')[0] && (
                    <Row style={{ height: 120 }}>
                      <Col span="11" style={{ textAlign: 'center' }}>
                        <Image
                          height={100}
                          width={100}
                          src={form.getFieldValue('att')[0] && form.getFieldValue('att')[0].url}
                          alt="暂无封面"
                        />
                      </Col>
                      <Divider type="vertical" style={{ height: 120 }} />
                      <Col span="10" offset="2">
                        <pre style={{ whiteSpace: 'pre-wrap', wordWrap: 'break-word' }}>
                          {form.getFieldValue('att1')}
                        </pre>
                      </Col>
                    </Row>
                  )}
                  <Divider /> */}
                {form.getFieldValue('attachment') && (
                  <Row>
                    <div style={{ textAlign: 'left', margin: '20px 0px 10px 10px' }}>
                      附件下载：
                      {form.getFieldValue('attachment').map(item => (
                        <div>
                          <a href={item.url} target="_blank" rel="noreferrer" download="下载">
                            {item.name}
                          </a>
                        </div>
                      ))}
                    </div>
                    )
                  </Row>
                )}
              </div>
            </div>
          )}
        </Form>
      </div>
    </Modal>
  );
};

export default connect(({ informationOpen, loading }) => ({
  loading: loading.effects['informationOpen/addCares'],
  pubList: informationOpen.pubList,
}))(LegalAffairsAddModal);
